# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import csv
import hashlib
import json
import os

from redis import StrictRedis
from scrapy.exceptions import DropItem


class KuaikanPipeline:
    def __init__(self, *args):
        print("创建文件夹")
        self.file_path = os.getcwd() + '/download/'
        if not os.path.exists(self.file_path):
            os.makedirs(self.file_path)
        self.img_path = self.file_path + 'images/'
        if not os.path.exists(self.img_path):
            os.makedirs(self.img_path)

    def open_spider(self, spider):
        if not os.path.exists(self.file_path + '快看_实事_1203.csv'):
            self.f = open(self.file_path + '快看_实事_1203.csv', 'a')
            self.f_csv = csv.DictWriter(self.f, ['title', 'news_url'])
            self.f_csv.writeheader()
        else:
            self.f = open(self.file_path + '快看_实事_1203.csv', 'a')
            self.f_csv = csv.DictWriter(self.f, ['title', 'news_url'])

    def close_spider(self, spider):
        self.f.close()

    def process_item(self, item, spider):
        msg_type = item.get('type')
        if msg_type == 'info':
            print("保存数据:", item)
            item.pop('type')
            self.f_csv.writerows([item])
        elif msg_type == 'img':
            img_name = item.get('img_name')
            img_bytes = item.get('img_bytes')
            with open(self.img_path + img_name, "wb") as f:
                f.write(img_bytes)
                print(img_name)
